// src/store/modelStore.ts
import { defineStore } from 'pinia'
import { changeUrl } from '@/api/chat'
export interface Model {
  id: string
  name: string
  endpoint: string
  apiUrl: string
  secretKey: string
  temperature: number
  top_p: number
  max_tokens: number
  repetition_penalty: number
  top_k: number
  min_p: number
  connectionType: String
}

export const useModelStore = defineStore('model', {
  state: () => ({
    models: [] as Model[],
    selectedModelId: null as string | null,
    needRefresh: false,
  }),
  actions: {
    addModel(newModel: Omit<Model, 'id'>) {
      const model: Model = {
        ...newModel,
        id: Date.now().toString()
      }
      this.models.push(model)
      this.persistModels()
    },
    deleteModel(modelId: string) {
      this.models = this.models.filter(m => m.id !== modelId)
      this.persistModels()
    },
    updateModel(model: Model){
      const index = this.models.findIndex(m => m.id === model.id)
      if (index >= 0) this.models.splice(index, 1, model)
      this.persistModels()
      this.needRefresh = true; // 设置刷新标志
    },
    loadModels() {
      const saved = localStorage.getItem('models')
      if (saved) this.models = JSON.parse(saved)
    },
    persistModels() {
      localStorage.setItem('models', JSON.stringify(this.models))
    },
    selectModel(modelId: string) {
      this.selectedModelId = modelId
      const selectedModel = this.models.find(m => m.id === modelId)
      if (selectedModel) {
        selectedModel.apiUrl = '/chatApi'+selectedModel.apiUrl
        localStorage.setItem('selectedModel', JSON.stringify(selectedModel))
        changeUrl(selectedModel)
      }
    }
  },
  getters: {
    selectedModel(): Model | undefined {
      return this.models.find(m => m.id === this.selectedModelId)
    }
  }
})
